// 修改记录

const { N, needParam } = require("../../utils");
const { getWhereStr, getIsSqlVar } = require("./_utils");
const { getSomeFieldNames, getStandFieldNames } = require("../../compile/mysql/_utils");

module.exports = {
  /**
   * 获取要修改字段的字符串
   * @param {object} fieldMap 要修改的字段信息
   * @returns
   */
  getUpdateFieldsStr(fieldMap = {}) {
    return Object.entries(fieldMap)
      .map(arr =>
        arr
          .map((it, i) => {
            if ((i === 0 || getIsSqlVar(it), true)) return it;
            return `'${it}'`;
          })
          .join(" = ")
      )
      .join(", ");
  },
  /**
   * 修改表格数据
   * @param {string} name 表名称
   * @param {object} fieldMap 要修改的字段数据
   * @param {object} { where, order, limits, group, having } sql配置
   */
  // 使用示例：updateTable('user', { gender: 2 }, {where: { user_name: "李四" }})
  updateTable(name = needParam(), fieldMap = needParam(), { where, order, limits, group, having }) {
    const fieldsStr = module.exports.getUpdateFieldsStr(fieldMap);
    // return `UPDATE ${name}${N}SET ${fieldsStr}${N}WHERE ${getWhereStr(where, getStandFieldNames(["*"], name))};`;
    let sql = `UPDATE ${name}${N}SET ${fieldsStr}`;
    const whereStr = getWhereStr(where, getStandFieldNames(["*"], name));
    if (whereStr) sql += `${N}WHERE ${whereStr}`;
    return `${sql};`;
  },
};
